package com.phkj.qdh.ui.fragment.instructionsheet

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.QuickAdapterHelper
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.bean.FileUploadBean
import com.phkj.qdh.bean.InstructionBean
import com.phkj.qdh.databinding.FragmentInstructionSheetHandleBinding
import com.phkj.qdh.net.FILE_UPLOAD
import com.phkj.qdh.net.msg
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAddAdapter
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.utils.FileHelper
import com.phkj.qdh.utils.GetImgContract
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.TakePhoto
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.requestMain
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import rxhttp3.RxHttp
import rxhttp3.toFlowResponse
import java.io.File
import java.text.SimpleDateFormat
import java.util.GregorianCalendar
import java.util.HashMap
import java.util.Locale

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 警情处理
 */
class InstructionSheetHandleFragment : Fragment() {
    private var _binding: FragmentInstructionSheetHandleBinding? = null
    private val binding get() = _binding!!
    private var param1: InstructionBean? = null
    private var param2: String? = null
    private lateinit var vm: InstructionVM
    private val iVAdapter by lazy { ImagerViewAdapter() }
    private val iVAddAdapter by lazy { ImagerViewAddAdapter() }
    private var imageUri: Uri? = null
    private var filePath: String = ""
    private val takePic =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { boolean ->
            if (boolean) {
                try {
                    imageUri?.let { uri ->
                        val option = BitmapFactory.Options()
                        option.inPreferredConfig = Bitmap.Config.RGB_565
                        val bitmap = BitmapFactory.decodeStream(
                            requireContext().contentResolver.openInputStream(uri)
                            ,null,option
                        )
                        val yasuohou = TakePhoto.scaleBitmap(bitmap,0.5f)
                        val path = TakePhoto.saveBitmap2File(yasuohou)
                        uploadImg(path)
                    }

                } catch (e: Exception) {

                }
            }
        }


    private val selectImg = registerForActivityResult(GetImgContract()) { uri ->
        uri?.let {
            LogUtil.E(it.toString())
            val file = FileHelper.getFileAbsolutePath(requireContext(), it)
            uploadImg(file)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getParcelable(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentInstructionSheetHandleBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getInstructionVMProvider())[InstructionVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rvLawSubmit.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(requireContext(), R.color.transparent),
                        28,
                        RecyclerView.HORIZONTAL
                    )
                )
            }
            btnOk.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("提交", "确定要提交反馈吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        save()
                    }

                    override fun dCancel() {
                    }

                })
                dialog.show(parentFragmentManager, "")

            }
        }

        val helper = QuickAdapterHelper.Builder(iVAdapter).build()
        helper.addBeforeAdapter(iVAddAdapter)
        iVAddAdapter.add("s")
        binding.rvLawSubmit.adapter = helper.adapter

        iVAdapter.addOnItemChildClickListener(R.id.iv_delete){adapter,_,pos->
            val dialog = CommonConfirmDialog.getInstance(
                "删除图片", "确定要删除图片吗", "确定", "取消"
            )
            dialog.setCancelListener(object : CommonConfirmListener {
                override fun dOk() {
                    adapter.removeAt(pos)
                }

                override fun dCancel() {
                    takePhoto()
                }

            })
            dialog.show(parentFragmentManager, "")
        }

        iVAddAdapter.setOnItemClickListener { adapter, data, pos ->
            if (iVAdapter.items.size >= 6) {
                ToastUtils.show("图片数量不能超过6张")
                return@setOnItemClickListener
            }
            XXPermissions.with(requireContext())
                .permission(arrayListOf(Permission.READ_MEDIA_IMAGES, Permission.CAMERA))
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (allGranted) {
                            val dialog = CommonConfirmDialog.getInstance(
                                "上传图片", "请选择上传方式", "选择照片", "拍照"
                            )
                            dialog.setCancelListener(object : CommonConfirmListener {
                                override fun dOk() {
                                    selectImg.launch(null)
                                }

                                override fun dCancel() {
                                    takePhoto()
                                }

                            })
                            dialog.show(parentFragmentManager, "")
                        }
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        super.onDenied(permissions, doNotAskAgain)
                    }
                })
        }

        launchAndRepeatWithViewLifecycle {
            vm.instructionReHandleResult.collectLatest {
                if (it) {
                    ToastUtils.show("反馈成功")
                    parentFragmentManager.popBackStack("detail",FragmentManager.POP_BACK_STACK_INCLUSIVE)
                }
            }
        }
    }


    private fun takePhoto() {
        val simpleDate = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        val fileName = simpleDate.format(GregorianCalendar().time) + ".jpg"
        var outputImage = File(requireContext().externalCacheDir, fileName)
        if (outputImage.exists()) {
            outputImage.delete()
        }
        outputImage.createNewFile()
        imageUri = if (Build.VERSION.SDK_INT >= 24) {
            FileProvider.getUriForFile(
                requireContext(), "com.phkj.qdh.fileprovider", outputImage
            )
        } else {
            Uri.fromFile(outputImage)
        }
        filePath = outputImage.absolutePath
        takePic.launch(imageUri)

    }

    private fun uploadImg(path: String) {
        requestMain {
            RxHttp.postForm(FILE_UPLOAD).addFile("file", path).toFlowResponse<FileUploadBean>()
                .catch { cause ->
                    ToastUtils.show(cause.msg)
                }.collectLatest {
                    delay(500)
                    iVAdapter.add(it.url)
                }
        }
    }

    private fun save() {
        if (iVAdapter.items.isEmpty()){
            ToastUtils.show("请上传图片")
            return
        }
        val map = HashMap<String, Any?>()
        map["problemId"] = param1?.id
        map["responsiblePerson"] = param1?.policeId
        map["feedback"] = binding.edt.text.toString()
        map["images"] = iVAdapter.items
        vm.saveInstructionReject(map)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: InstructionBean, param2: String) =
            InstructionSheetHandleFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}